package com.czy.moudle.pdm.service.impl;

import com.czy.moudle.pdm.service.DataTranceService;
import com.czy.moudle.pdm.vo.Entity;
import com.czy.moudle.pdm.vo.Field;
import com.czy.util.StringUtils;
import org.apache.commons.collections.CollectionUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

/**
 * 数据转换实现类
 *
 * @author 陈致远
 */
public class DataTranceServiceImpl implements DataTranceService {

    @Override
    public String column2FieldOfName(String dbName) {
        if (dbName.contains(SPLIT_STR)) {
            //1.转换表名称为字符串数组，以_分割
            String[] array = dbName.split(SPLIT_STR);

            //2.遍历数组，从下标1开始（过滤掉T_开头）
            StringBuffer strBuffer = new StringBuffer();
            for (int i = 1; i < array.length; i++) {
                //3.拼接类名称，数组中每个元素首字母大写，其他小写
                strBuffer.append(StringUtils.firstChar2UpperAndOthersLower(array[i]));
            }

            return strBuffer.toString();
        } else {
            return dbName;
        }

    }

    @Override
    public String column2FieldOfType(String columnType) {
        //1.读取类型映射配置文件
        Properties typeMapped = new Properties();
        InputStream inputStream = this.getClass().getResourceAsStream("/type-mapped.properties");

        try {
            typeMapped.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Enumeration enums = typeMapped.propertyNames();

        //2.遍历配置信息，匹配合适的类型
        while (enums.hasMoreElements()) {
            String javaType = (String) enums.nextElement();
            String[] pdmTypeArray = typeMapped.getProperty(javaType).split(",");

            for (String pdmType : pdmTypeArray) {
                if (columnType.matches(pdmType)) {
                    return javaType;
                }
            }
        }

        return "String";
    }

    @Override
    public void tranceDBColumnList(List<Entity> tableList) {
        if (CollectionUtils.isNotEmpty(tableList)) {
            for (Entity table : tableList) {
                table.setClassName(this.column2FieldOfName(table.getTableName()));

                List<Field> columnList = table.getColumnList();
                if (CollectionUtils.isNotEmpty(columnList)) {
                    for (Field column : columnList) {
                        column.setFieldName(this.column2FieldOfName(column.getColumnName()));
                        column.setFieldType(this.column2FieldOfType(column.getColumnType()));
                    }
                }
            }
        }
    }

}
